//
//  CollisionDelegate.m
//  MessangerSkeleton
//
//  Created by User-16 on 4/24/14.
//  Copyright (c) 2014 IOTrainingCamp. All rights reserved.
//

#import "CollisionDelegate.h"
#import "MessengerSprite.h"
#import "IntroScene.h"
#import "GameScene.h"
#import "GamePlay.h"
#import <Social/Social.h>
#import <Accounts/Accounts.h>

#import "NetworkManager.h"

@interface CollisionDelegate ()

@property(nonatomic) UIAlertView* finishLineCrossed;

@end

@implementation CollisionDelegate

//obstacle -> rock and stalaktit
-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair player:(CCNode *)nodeA obstacle:(CCNode *)nodeB
{

    
    
    MessengerSprite* player= (MessengerSprite*) nodeA;
    [player unschedule:@selector(restoreKikback)];
    
    NSLog(@"%f < %f < %f : %f < %f <  %f", player.front.begining.x, pair.contacts.points[0].pointA.x, player.front.end.x, player.front.begining.y, pair.contacts.points[0].pointA.y, player.front.end.y);

    
      //NSLog(@"%d", player.state);
    
    if(player.lastHitObstacle == nodeB) return NO;

        player.lastHitObstacle = nodeB;

        if([self isPoint:pair.contacts.points[0].pointA withinInterval:player.front] || [self isPoint:pair.contacts.points[0].pointA withinInterval:player.back])
        {
            NSLog(@"front or back hit");
        [player hitToFrontOrBack];
        }

        if([self isPoint:pair.contacts.points[0].pointA withinInterval:player.bottom])
        {
            NSLog(@"hit bottom");
                player.hitBottom = YES;
                [player hitToBottom];
        }

        if([self isPoint:pair.contacts.points[0].pointA withinInterval:player.up])
        {
            NSLog(@"hit up");
                [player hitToTop];
        }
    
    //NSLog(@"%d", player.state);

    return NO;   
}



-(BOOL) isPoint:(CGPoint) point withinInterval:(Interval) interval{

        if(point.x < interval.begining.x) return NO;
        if(point.x > interval.end.x)  return NO;
        if(point.y < interval.begining.y) return NO;
        if(point.y > interval.end.y) return NO;
    
    TransferSettings* transferedData = [TransferSettings sharedInstance];
    if (transferedData.soundsOn) {
        [[OALSimpleAudio sharedInstance] playEffect:kPreloadEffectBump];
    }
        return YES;
}

-(void)ccPhysicsCollisionSeparate:(CCPhysicsCollisionPair *)pair player:(CCNode *)nodeA obstacle:(CCNode *)nodeB
{
    MessengerSprite* player = (MessengerSprite*) nodeA;
    if(player.hitBottom)
        {
                player.hitBottom = NO;
                [player endHitToBottom];
        }
}

//finish line
-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair player:(CCNode *)nodeA finishLine:(CCNode *)nodeB
{
    
    NSLog(@"player crossed finish line");
    GamePlay* gamePlay = [GamePlay sharedInstance];
    MessengerSprite* player = (MessengerSprite*) nodeA;
    TransferSettings* transferedData = [TransferSettings sharedInstance];
    if (transferedData.soundsOn) {
        [[OALSimpleAudio sharedInstance] playEffect:kPreloadEffectWin];
    }
    if (!transferedData.gameEnded) {
        if (gamePlay.gamePosition == GamePlaySingleplayer) {
            [self finishLineHasBeenCrossedByPlayer:player];
        }
        else if (gamePlay.gamePosition == GamePlayMultiplayer) {
            if (gamePlay.characterType == player.characterType) {
                NSLog(@"I'm self, I won!");
                UIAlertView* iWonMultiplayer = [[UIAlertView alloc] initWithTitle:kAlertViewDefaultTitle message:[NSString stringWithFormat: @"I won a multiplayer match of Messenger with time:%.2f",player.secondsPassedSinceStart] delegate:self cancelButtonTitle:kAlertViewMenuButtonTitle otherButtonTitles: nil];
                [iWonMultiplayer show];
            }
            else {
                NSLog(@"I lost");
                UIAlertView* iLostMultiplayer = [[UIAlertView alloc] initWithTitle:@"You lose" message:[NSString stringWithFormat:@"I've just played multiplayer match of Messenger"] delegate:self cancelButtonTitle:kAlertViewMenuButtonTitle otherButtonTitles: nil];
                [iLostMultiplayer show];
                [(NetworkManager *)[NetworkManager sharedInstance]  performSelector:@selector(endSession) withObject:nil afterDelay:5];
            }
        }
        transferedData.gameEnded = YES;
    }

    return NO;

}

-(void)ccPhysicsCollisionSeparate:(CCPhysicsCollisionPair *)pair player:(CCNode *)nodeA finishLine:(CCNode *)nodeB
{
    MessengerSprite* player = (MessengerSprite*) nodeA;
    player.paused = NO;
}

//other player crossed finish line



//power up -> speed boost
-(BOOL)ccPhysicsCollisionBegin:(CCPhysicsCollisionPair *)pair player:(CCNode *)nodeA powerUpSpeedBoost:(CCNode *)nodeB
{
    MessengerSprite* player = (MessengerSprite*) nodeA;
    [player collectPowerUpSpeedBoostItem];
    [nodeB removeFromParent];
    
    return NO;
}

-(void)ccPhysicsCollisionSeparate:(CCPhysicsCollisionPair *)pair player:(CCNode *)nodeA powerUpSpeedBoost:(CCNode *)nodeB
{
    MessengerSprite* player = (MessengerSprite*) nodeA;
    player.paused = NO;
}

//----------------------------------------------------------------------------------------

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if ([alertView.title isEqualToString:kAlertViewDefaultTitle] || [alertView.title isEqualToString:kAlertViewNewHighScoreTitle] || [alertView.title isEqualToString:@"You lose"]) {
        SWITCH([alertView buttonTitleAtIndex:buttonIndex]){
            CASE (kAlertViewMenuButtonTitle) {
                [self onBackClicked:self];
                break;
            }
            CASE(kAlertViewShareButtonTitle) {
                [self shareOnFacebook];
                break;
            }
            CASE(kAlertViewPlayAgainButtonTitle) {
                [self playAgainClicked];
                break;
            }
            DEFAULT {
                break;
            }
        }
        //end of finishLineCrossed alertView
    }
    else if ([alertView.title isEqualToString:@"No Account"]) {
        SWITCH([alertView buttonTitleAtIndex:buttonIndex]) {
            CASE(@"Ok") {
                [self.finishLineCrossed show];
                break;
            }
            DEFAULT {
                break;
            }
        }
    }
    
}

//play again the current level
- (void) playAgainClicked {
    [[CCDirector sharedDirector] replaceScene:[GameScene sceneWithLevel:1]
                               withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionRight duration:1.0f]];
}

//return to menu
- (void)onBackClicked:(id)sender
{
    // back to intro scene with transition
    [[CCDirector sharedDirector] replaceScene:[IntroScene scene]
                               withTransition:[CCTransition transitionPushWithDirection:CCTransitionDirectionRight duration:1.0f]];
}

//share on facebook
//refactor this with viable game data :) -> Time Points / Beat somebody for multiplayer etc.
- (void)shareOnFacebook {
    if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
        SLComposeViewController* mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
        [mySLComposerSheet setInitialText:@"I invite you to play The Messenger!"];
//        [mySLComposerSheet addImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"Icon-72@2x.png"]]]];
        [mySLComposerSheet addImage:[UIImage imageNamed:@"Icon-72@2x.png"]];
        [mySLComposerSheet addURL:[NSURL URLWithString:@""]];
        [mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result){
            switch (result) {
                case SLComposeViewControllerResultCancelled:
                    [self onBackClicked:self];
                    break;
                case SLComposeViewControllerResultDone:
                    [self onBackClicked:self];
                    break;
                    
                default:
                    break;
            }
        }];
        [[CCDirector sharedDirector] presentViewController:mySLComposerSheet animated:YES completion:nil];
    }
    else {
        UIAlertView* notLoggedInFacebookAlertView = [[UIAlertView alloc] initWithTitle:@"No Account" message:@"Please log-in to facebook from device settings." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
        [notLoggedInFacebookAlertView show];
    }
}

-(void) finishLineHasBeenCrossedByPlayer:(MessengerSprite*) player {
    NSString* finishLineCrossedMessage = [[NSString alloc] init];
    NSString* finishLineCrossedTitle = [[NSString alloc] init];
    
    GamePlay* currentGameplay = [GamePlay sharedInstance];
    int currentLevel = currentGameplay.level;
    
    CGFloat highScoreForCurrentLevel = [[NSUserDefaults standardUserDefaults] floatForKey:[NSString stringWithFormat:@"%d",currentLevel]];
    if ((int)highScoreForCurrentLevel == 0) {
        highScoreForCurrentLevel = NSIntegerMax;
    }
    
    if (highScoreForCurrentLevel > player.secondsPassedSinceStart){
        //if highscore -> new messege for the alert view
        highScoreForCurrentLevel = player.secondsPassedSinceStart;
        finishLineCrossedMessage = [kAlertViewNewHighScoreMessage stringByAppendingString:[NSString stringWithFormat:@"\nHighScore: %.2f",highScoreForCurrentLevel]];
        finishLineCrossedTitle = kAlertViewNewHighScoreTitle;
    }
    else {
        //if not highscore -> default messege for the alert view
        finishLineCrossedMessage = [kAlertViewDefaultMessage stringByAppendingString:[NSString stringWithFormat:@"\nHighScore: %.2f\nYour Score:%.2f",highScoreForCurrentLevel,player.secondsPassedSinceStart]];
        finishLineCrossedTitle = kAlertViewDefaultTitle;
    }
    
    [[NSUserDefaults standardUserDefaults] setFloat:highScoreForCurrentLevel forKey:[NSString stringWithFormat:@"%d",currentLevel]];
    NSLog(@"%f",[[NSUserDefaults standardUserDefaults] floatForKey:[NSString stringWithFormat:@"%d",currentLevel]]);
    
    self.finishLineCrossed = [[UIAlertView alloc] initWithTitle:finishLineCrossedTitle message:finishLineCrossedMessage delegate:self cancelButtonTitle:kAlertViewMenuButtonTitle otherButtonTitles: kAlertViewPlayAgainButtonTitle, kAlertViewShareButtonTitle, nil];
    [self.finishLineCrossed show];
}

@end
